package com.rcm.dda.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.rcm.dda.exception.DDAValidationException;
import com.rcm.dda.json.response.JsonResponse;
import com.rcm.dda.json.response.JsonResponseError;
import com.rcm.dda.json.response.JsonResponseErrorEnum;
import com.rcm.dda.model.RateKey;
import com.rcm.dda.service.RateKeyService;

@RestController
@RequestMapping("/ratekey")
public class RateKeyController {

	@Autowired
	private RateKeyService rateKeyService;

	@RequestMapping(method = RequestMethod.GET)
	public JsonResponse get() {
		JsonResponse jsonResponse = new JsonResponse();
		jsonResponse.setReturnObject(rateKeyService.getAll());
		jsonResponse.setStatus(JsonResponse.STATUS_SUCCESS);
		return jsonResponse;
	}

	@RequestMapping(method = RequestMethod.PUT)
	public JsonResponse insert(@RequestBody RateKey rateKey) {
		try {
			JsonResponse jsonResponse = new JsonResponse();
			jsonResponse.setReturnObject(rateKeyService.insert(rateKey));
			jsonResponse.setStatus(JsonResponse.STATUS_SUCCESS);
			return jsonResponse;
		} catch (Exception e) {
			return handleException(e);
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public JsonResponse update(@RequestBody RateKey rateKey) {
		try {
			JsonResponse jsonResponse = new JsonResponse();
			jsonResponse.setReturnObject(rateKeyService.update(rateKey));
			jsonResponse.setStatus(JsonResponse.STATUS_SUCCESS);
			return jsonResponse;
		} catch (Exception e) {
			return handleException(e);
		}
	}

	@RequestMapping(method = RequestMethod.DELETE)
	public JsonResponse delete(@RequestBody RateKey rateKey) {
		try {
			JsonResponse jsonResponse = new JsonResponse();
			rateKeyService.delete(rateKey);
			jsonResponse.setStatus(JsonResponse.STATUS_SUCCESS);
			return jsonResponse;
		} catch (Exception e) {
			return handleException(e);
		}
	}

	private JsonResponse handleException(Exception e) {
		JsonResponse jsonResponse = new JsonResponse();
		jsonResponse.setStatus(JsonResponse.STATUS_FAIL);
		if (e instanceof DuplicateKeyException) {
			jsonResponse.setReturnObject(new JsonResponseError(
					JsonResponseError.DUPLICATE,
					JsonResponseErrorEnum.DUPLICATED_KEY.getErrorCode()));
		} else if (e instanceof DDAValidationException) {
			jsonResponse.setReturnObject(new JsonResponseError(
					JsonResponseError.VALIDATION, ((DDAValidationException) e)
							.getUnit()));
		} else {
			jsonResponse.setReturnObject(new JsonResponseError(
					JsonResponseError.UPDATE_FAILED, null));
			System.out.println(e);
		}
		return jsonResponse;
	}
}
